package com.example.baselib

import android.app.Application
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.*
import com.example.baselib.dialog.LoadingDialog

import kotlinx.coroutines.*
import java.lang.Exception



/**
 * @author sxygsj.
 * @creat time 2020/4/14 8:57.
 * @description [网络请求 baseviewmode]
 * @chang time 2020/4/14 8:57.
 * @chang describe []
 */
open class BaseViewModel(application: Application): AndroidViewModel(application), LifecycleObserver {
    private lateinit var fragmentManager: FragmentManager
    private lateinit var loadingDialog: LoadingDialog
    private lateinit var error :MutableLiveData<Exception>
    private lateinit var finally:MutableLiveData<Int>
    var isLoad=true
    //运行在UI线程的协程
    fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch {
        try {
            if(isLoad)loadingDialog.show(fragmentManager,"Job") else isLoad=true
            withTimeout(10000){
                block()
            }
        }
        catch (e: Exception) {
            error.value = e
        }
        finally {
            finally.value = 200
        }
    }
    /**
     * 请求失败，出现异常
     */
    fun getError(): LiveData<Exception> {
        error=MutableLiveData<Exception>()
        return error
    }

    /**
     * 请求完成，在此处做一些关闭操作
     */
    fun getFinally(): LiveData<Int> {
        finally=MutableLiveData<Int>()
        return finally
    }

    fun setFragmentManager(loadingDialog: LoadingDialog,supportFragmentManager: FragmentManager){
        this.loadingDialog=loadingDialog
        this.fragmentManager=supportFragmentManager
    }
}